import {
  Toast,
  MessageBox
} from "mint-ui";

const wx = require("weixin-js-sdk");
import CONFIG from "../js/CONFIG.js";

// import QRCode from 'qrcode'; // 二维码
// import { Loadmore } from 'mint-ui';// 
export default {
  install: function (Vue, opt) {
    Vue.mixin({
      data() {
        return {
          provinceList: [], //省份数据
          cityList: [], //城市数据
          districtList: [], // 县市数据
          page: 0, //当前页码
          limit: 10, //每页条数
          totalPage: 0, //总页码
          topStatus: "", //刷新
          //加载更多
          queryLoading: false,
          moreLoading: false,
          allLoaded: false,
        }
      },
      methods: {
        JumpToWeCaht() {
          let THIS = this;
          let returnURL = CONFIG.WeChat.WeChatOauth;
    
          // THIS.setLCDATABEFORELOGO();
    
          let _uid = this.$route.query.yqid || 1;
    
          // return false
          window.location.href =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
            CONFIG.WeChat.appid +
            "&redirect_uri=" +
            returnURL +
            "&response_type=code&scope=snsapi_userinfo&state=" +
            _uid +
            "#wechat_redirect";
        },

        //刷新
        handleTopChange(status) {
          this.topStatus = status;
        },
        // 路由跳转
        toRouter(url, query = {}) {
          // alert(JSON.stringify(ops));
          this.$router.push({
            path: `/${url}`,
            query
          });
        },
        back() {
          this.$router.back(-1)
        },
        isString(obj){ //判断对象是否是字符串  
          return Object.prototype.toString.call(obj) === "[object String]";  
        },

        /**
         * 本地储存封装
         */
        // 读取缓存
        getCache(name) {
          // 读取缓存
          if (!name) {
            console.warn("读取缓存时发生错误");
            return false;
          }

          try {
            return JSON.parse(localStorage[name]);
          } catch (error) {
            return localStorage[name];
          }
        },

        // 设置缓存
        setCache(name, value) {
          if (!name) {
            console.warn("设置缓存时发生错误");
            return false;
          }

          console.log("设置了缓存", name, value);
          if (typeof value == "object") {
            value = JSON.stringify(value);
          }

          localStorage[name] = value;
        },

        // 移除缓存
        removeCache(name) {
          // 移除缓存
          if (!name) {
            console.warn("移除缓存失败");
            return false;
          }

          localStorage.removeItem(name);
          console.log("移除了缓存:" + name);
        },


        /**
         * 一些正则验证
         * 及其他验证
         */
        // 是否是手机号
        hasMobile(phone) {
          let re = /^[1][34587]\d{9}$/ //手机号码验证正则表达式return
          if (re.test(phone)) {
            return true;
          } else {
            return false;
          }
        },

        // 身份证验证
        hasUserCode(val) {
          var regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
          if (!regIdNo.test(val)) {
            return false;
          } else {
            return true;
          }
        },

        /***
         * 一些公共方法
         */
        // 是否还有更多分页
        hasPage(has) {
          let page = (this.page = ++this.page);
          if (has && page > this.totalPage) {
            this.layer("已加载全部");
            this.allLoaded = true;
            return false;
          }
          return page;
        },
        // 去除字符串中所有空格
        removeAllSpace(str) {
          return str.replace(/\s+/g, "");
        },
        // 时间格式化过滤器，输入时间戳或Dade对象，输出'yyyy-MM-dd hh:mm:ss'
        toDate(val, type = 'yyyy-MM-dd hh:mm:ss') {
          let time = new Date(val).getTime() || new Date().getTime();
          return new Date(time).format(type);
        },
        // 返回url参数的对象
        getRequest(url) {
          let theRequest = new Object();
          let strs = url.split("&");
          for (let i = 0; i < strs.length; i++) {
            if(strs[i].split("=")[1] === 'null'){
              theRequest[strs[i].split("=")[0]] = 0;
            } else {
              theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
           
          }
          return theRequest;
        },

        /**
         * mint UI 样式封装
         *  Toast、alert、confirm、prompt
         */
        layer(text, type = 'm') {
          let position = {
            't': "top",
            'b': "bottom",
            'm': "middle"
          }
          Toast({
            message: text,
            position: position[type],
            duration: 3000
          });
        },

        alert(val, type = '1', fuc = () => {}) {
          let i = parseInt(type);
          switch (i) {
            case 1:
              MessageBox.alert(val).then(res => {
                fuc();
              });
              break;
            case 2:
              MessageBox.confirm(val).then(res => {
                fuc();
              });
              break;
            default:
              MessageBox.prompt(val).then(({
                value,
                action
              }) => {
                fuc(value);
              });
          }
        },


        //省
        getProvince() {
          let that = this;
          this.http
            .get("province/list", {
              location: true
            })
            .then(res => {
              that.provinceList = res.provinceList;
            })
            .catch(err => {});
        },
        //城市
        getCity(id, has = 0) {
          let that = this;
          this.http
            .get("city/list", {
              location: true,
              provinceid: id
            })
            .then(res => {
              has ? that.cityList1 = res.cityList : that.cityList = res.cityList;
            })
            .catch(err => {});
        },
        //区
        getDistrict(id, has = 0) {
          let that = this;
          this.http
            .get("district/list", {
              location: true,
              cityid: id
            })
            .then(res => {
              has ? that.districtList1 = res.districtList : that.districtList = res.districtList;
            })
            .catch(err => {});
        },
        //获取省份名字，并获取对应的城市
        /**
         * 获取省份，城市，区域，并根据id获取对应名字
         * @param {*} itName 保存数据状态的对象
         * @param {*} index  1=省，2=市，区的标识
         * @param {*} has  1=省，2=市，投资意向区域
         */
        changeSiteInfo(itName, index = 0, has = 0) {
          let that = this;
          if (index === 1) {
            let id;
            if (has) {
              id = this[itName].investLikesProvinceCode;
              that.getCity(id, 1);
            } else {
              id = this[itName].provinceid;
              that.getCity(id);
            }

            // that.districtList = [];
            for (let i = 0; i < this.provinceList.length; i++) {
              if (id == that.provinceList[i].provinceid) {
                if (has) {
                  that[itName]["investLikesProvinceName"] = that.provinceList[i].provinceName;
                } else {
                  that[itName]["provinceName"] = that.provinceList[i].provinceName;
                }
                break;
              }
            }
          } else if (index === 2) {
            let id;
            if (has) {
              id = this[itName].investLikesCityCode;
              that.getDistrict(id, 1);
              for (let i = 0; i < this.cityList1.length; i++) {
                if (id == that.cityList1[i].cityid) {
                  that[itName]["investLikesCityName"] = that.cityList1[i].cityname;
                  break;
                }
              }
            } else {
              id = this[itName].cityid;
              that.getDistrict(id);
              for (let i = 0; i < this.cityList.length; i++) {
                if (id == that.cityList[i].cityid) {
                  that[itName]["cityName"] = that.cityList[i].cityname;
                  break;
                }
              }
            }

          } else {
            let id;
            if (index === 4) { // 添加客户，投资意向区域
              id = this[itName].investLikesDistrictCode;
              for (let i = 0; i < this.districtList1.length; i++) {
                if (id == that.districtList1[i].districtid) {
                  that[itName]["investLikesDistrictName"] = that.districtList1[i].districtname;
                  break;
                }
              }
            } else {
              id = this[itName].districtid;
              for (let i = 0; i < this.districtList.length; i++) {
                if (id == that.districtList[i].districtid) {
                  that[itName]["districtName"] = that.districtList[i].districtname;
                  break;
                }
              }
            }
          }
        },

        /*//二维码
        qrcode(str) {
            QRCode.toDataURL(str)
            .then(url => {
              console.log('二维码000000000=='+url)
              return url;
            })
            .catch(err => {
              console.error('二维码1111111111=='+err)
            })
        }*/

        // 获取用户最新信息
        updateUserInfo() {
          let that = this;
          this.http.post('user/userInfo').then(res => {
            if (res.code === 0) {
              that.setCache('userInfo', res.data);
            }
          })
        },
      },
      filters: {
        // 过滤时间，处理
        toTime(val, type = 'yyyy-MM-dd hh:mm:ss') {
          let time = new Date(val).getTime() || new Date().getTime();
          if (!val) {
            time = new Date().getTime();
          }
          return new Date(time).format(type);
        },
        // 手机号隐藏中间四位
        toMobile(val) {
          return val.substr(0, 3) + '****' + val.substr(7);
        },
        /*//二维码
        qrcode(ops) {
            return QRCode.toDataURL(ops)
            .then(url => {
                console.log('二维码000000000=='+url)
              return url;
            });
        }*/
        // 看房状态 0已通话 1已匹配 2 已报备 3 已看房 4 已再次看房（查看再次看房的次数） 5 已签约 
        getLookStatus(i) {
          let lookHouseStatus = {
            '0': '已通话',
            '1': '已匹配',
            '2': '已报备',
            '3': '已看房',
            '5': '已签约'
          }
          if (!i) {
            i = '1'
          }
          return lookHouseStatus[i]
        },
        getMatchStatus(i) {
          let matchStatus = {
            "0": "未匹配",
            "1": "已匹配",
            // "2": "未匹配"
          };
          // if (!i) {
          //   i = "0";
          // }
          return matchStatus[i];
        },
        // 返回客户名字 第一个字符
        getClientName(str) {
          str = '' + str;
          return str.split('')[0];
        },
        //用户等级推客
        userRank(i) {
          let rank = {
            '1': '一级推客',
            '2': '二级推客',
            '3': '三级推客',
            '4': '四级推客',
            '5': '五级推客',
            '6': '六级推客',
            '7': '七级推客',
          }
          if (!i) {
            i = '1';
          }
          return rank[i]
        }
      }
    });
  }
}
